package com.example.nextstream.utils;

import com.alibaba.fastjson.JSONObject;

/**
 * 响应JSON消息构建体
 *
 * @author superjin
 */
public class RspBuilder {
    private static final String KEY_RESULT = "result";
    private static final String KEY_CODE = "code";
    private static final String KEY_MSG = "msg";
    private static final String RESULT_SUCCESS = "success";
    private static final String RESULT_FAIL = "fail";

    private JSONObject jobj;

    public RspBuilder() {
        this.jobj = new JSONObject();
    }

    /**
     * 追加响应键值对
     *
     * @param key
     * @param value
     * @return
     */
    public RspBuilder append(String key, Object value) {
        this.jobj.put(key, value);
        return this;
    }

    /**
     * 追加'code'为key的消息
     *
     * @param code
     * @return
     */
    public RspBuilder appendCode(String code) {
        this.jobj.put(KEY_CODE, code);
        return this;
    }

    /**
     * 追加'msg'为key的消息
     *
     * @param msg
     * @return
     */
    public RspBuilder appendMsg(String msg) {
        this.jobj.put(KEY_MSG, msg);
        return this;
    }

    /**
     * 设置成功响应
     *
     * @return
     */
    public RspBuilder setSuccessResult() {
        this.jobj.put(KEY_RESULT, RESULT_SUCCESS);
        return this;
    }

    /**
     * 设置失败响应
     *
     * @return
     */
    public RspBuilder setErrorResult() {
        this.jobj.put(KEY_RESULT, RESULT_FAIL);
        return this;
    }

    /**
     * 返回响应消息体
     *
     * @return
     */
    public JSONObject build() {
        return jobj;
    }

    /**
     * 构造成功响应Builder
     *
     * @return
     */
    public static RspBuilder createSuccessRsp() {
        return new RspBuilder().setSuccessResult();
    }

    /**
     * 构造错误响应JSONObject
     *
     * @param msg
     *            错误描述信息
     * @return
     */
    public static JSONObject formatFailResult(String msg) {
        return new RspBuilder().setErrorResult().appendMsg(msg).build();
    }

    /**
     * 构造默认成功JSONObject
     *
     * @return
     */
    public static JSONObject defaultSuccessResult() {
        return createSuccessRsp().build();
    }
}
